import { reactive, inject, provide } from 'vue';
import { ClassList, ClassParam, StuClass } from '../types/jobs/classList';
import { ConsoleLogger } from '@/utils/debug-log';
import { getClasslist } from '../api/classList';
import { Toast } from 'vant';

const console = new ConsoleLogger('班级列表');

export interface IClassListState {
  list?: Array<StuClass>;
  clssList?: ClassList | {};
  loading: boolean; // 是否加载中，非加载中loading为false,加载中为true
  finished: boolean; // 当finished为true时，不会再触发onLoad事件
  refreshing: boolean; // 当用户下拉时，refreshing自动为true
  status: 2 | 3; // 当前班级状态
  ongoing: number | string; // 进行中待批改个数
  ended: number | string; // 已结束待批改个数
}

export interface IUseClassListStore {
  state: IClassListState;
  toGetClasslist: () => Promise<void>;
  toClearlist: () => void;
  changeStatus: (param: 2 | 3) => void;
  toGetEndedNumber: () => void;
}
/**
 *  * useClassListStore 班级列表hooks.
 * @function
 * @params {IClassListState} userState - 班级列表信息.
 * @returns store extend IUseClassListStore
 */
export const useClassList: () => IUseClassListStore = () => {
  const state = reactive<IClassListState>({
    list: [],
    loading: false,
    finished: false,
    refreshing: false,
    status: 2,
    ongoing: 0,
    ended: 0
  });

  const toGetClasslist = async () => {
    if (!state.finished) {
      state.loading = true;
      const data = await getClasslist({
        class_type: state.status,
        last_class: (state.list && state.list.length > 0 && state.list[state.list.length - 1].id) || 0
      });
      if (data.code !== 0) {
        state.refreshing = false;
        state.loading = false;
        state.finished = true;
        Toast(data.msg);
        return;
      }
      state.refreshing = false;
      state.clssList = data.data;
      state.finished = !data.data.has_more;
      state.list = state.list?.concat(data.data.list);
      const text = state.status === 2 ? 'ongoing' : 'ended';
      state[text] = data.data.total_num > 99 ? '99+' : data.data.total_num;
      state.loading = false;
    }
  };

  const toClearlist = () => {
    state.refreshing = true;
    state.clssList = {};
    state.list = [];
    state.finished = false;
  };

  const changeStatus = (status: 2 | 3) => {
    state.refreshing = true;
    state.status = status;
    state.clssList = {};
    state.list = [];
    state.finished = false;
    toGetClasslist();
  };

  const toGetEndedNumber = async () => {
    const data = await getClasslist({
      class_type: 3,
      last_class: 0
    });
    if (data.code === 0) {
      state.ended = data.data.total_num > 99 ? '99+' : data.data.total_num;
    }
  };

  const store: IUseClassListStore = {
    state,
    toGetClasslist,
    toClearlist,
    changeStatus,
    toGetEndedNumber
  };
  return store;
};
